package com.ccys.doctor.controller;

import com.ccys.common.third.mailGun.MailgunUtil;
import com.ccys.common.vo.ResponseResultApp;
import com.ccys.db.cache.UserUtil;
import com.ccys.db.dto.doctor.postConsult.*;
import com.ccys.db.entity.TblBooking;
import com.ccys.db.entity.TblBookingSummary;
import com.ccys.db.entity.TblMember;
import com.ccys.db.mapper.TblDoctorSupportTabReadMapper;
import com.ccys.db.mapper.TblMemberMapper;
import com.ccys.db.page.AppPageDto;
import com.ccys.db.vo.doctor.postConsult.MemberInfoVo;
import com.ccys.db.vo.doctor.postConsult.SpecialistResVo;
import com.ccys.doctor.service.BookingService;
import com.ccys.doctor.service.BookingSummaryService;
import com.ccys.doctor.service.PDFDocumentService;
import com.ccys.doctor.service.PostConsultService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @Author：XLY
 * @Date：2024/2/7 0007
 */
@RestController
@RequestMapping("/postConsult")
@Api(tags = "Post consult")
@Slf4j
public class PostConsultController {


    @Resource
    private TblDoctorSupportTabReadMapper mapper;


    @Resource
    private PostConsultService service;


    @Resource
    private PDFDocumentService pdfDocumentService;

    @Resource
    private TblMemberMapper memberMapper;


    @Resource
    private BookingService bookingService;


    @Resource
    private BookingSummaryService bookingSummaryService;

    @ApiOperation("Post consult/ 1")
    @PostMapping("EmailMemoToClinic")
    public ResponseResultApp emailMemoToClinic(@RequestBody EmailMemoToClinicDto dto) {
        String memo_email_address = dto.getMemo_email_address();
        if (StringUtils.isNotEmpty(memo_email_address)) {
            //根据email找到这个人的info
            Example memberExample = new Example(TblMember.class);
            memberExample.createCriteria().andEqualTo("email", memo_email_address);
            List<TblMember> tblMembers = memberMapper.selectByExample(memberExample);
            if (CollectionUtils.isNotEmpty(tblMembers)) {
                TblMember member = tblMembers.get(0);
                //邮件主题名: "WhiteCoat Memo: " + memberName
                String subject = "WhiteCoat Memo: " + member.getFirstName() + " " + member.getLastName();
                //生成memoPDF的内容
                String emailContent = pdfDocumentService.generateCustomMemoPdf(dto.getBooking_id(), dto.getMemo());
                //发送邮件（附带文件）
                CompletableFuture.runAsync(() -> {
                    try {
                        //原版是用亚马逊s3根据file_path找到文件或者传byte数组
                        List<EmailMemoToClinicDto.AttachedFileVo> attached_files = dto.getAttached_files();
                        Map<String, String> map = attached_files.stream().collect(Collectors.toMap(EmailMemoToClinicDto.AttachedFileVo::getFile_name, EmailMemoToClinicDto.AttachedFileVo::getFile_path));
                        MailgunUtil.sendEmail(memo_email_address, subject, null, emailContent, map);

                    } catch (Exception e) {
                        log.error(e.getMessage());
                    }
                });
            }

        }
        //返回当前时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM dd yy HH:mm:ss");
        String format = simpleDateFormat.format(new Date());
        return ResponseResultApp.success(format);
    }

    @ApiOperation("Post consult/ 2")
    @PostMapping("ForwardReferralLetter")
    public ResponseResultApp ForwardReferralLetter(@RequestBody ForwardReferralLetterDto dto) {
        //生成ReferralLetter
        String bookingId = dto.getBooking_id();
        //邮件主题: "WhiteCoat Referral Letter: "+memberName
        MemberInfoVo memberInfo = memberMapper.getMemberInfoByBookingId(bookingId);
        String email = memberInfo.getEmail();
        if(StringUtils.isNotEmpty(email)){
            String subject = "WhiteCoat Referral Letter: " + memberInfo.getFirstName() + " " + memberInfo.getLastName();
            String emailContent = pdfDocumentService.generateReferralLetterHtml(bookingId);
            //发送邮件
            CompletableFuture.runAsync(() -> {
                try {
                    MailgunUtil.sendEmail(email, subject, null, emailContent);

                } catch (Exception e) {
                    log.error(e.getMessage());
                }
            });
        }
        return ResponseResultApp.success();
    }


    @ApiOperation("Post consult/ 3")
    @PostMapping("GenerateMedicalCertificate")
    public ResponseResultApp generateMedicalCertificate(@RequestBody GenerateMedicalCertificateDto dto) {

        return service.generateMedicalCertificate(dto);
    }


    @ApiOperation("Post consult/ 4")
    @PostMapping("GenerateMemo")
    public ResponseResultApp generateMemo(@RequestBody GenerateMemoDto dto) {
        return service.generateMemo(dto);
    }

    @ApiOperation("Post consult/ 5")
    @PostMapping("GenerateReferralLetter")
    public ResponseResultApp GenerateReferralLetter(@RequestBody GenerateReferralLetterDto dto) {

        return service.generateReferralLetter(dto);
    }


    @ApiOperation("Post consult/ 6")
    @GetMapping("GetSpecialist")
    public ResponseResultApp<SpecialistResVo> getSpecialist(GetSpecialistDto dto) {
        AppPageDto.startPage();
        List<SpecialistResVo.SpecialistVo> specialist = mapper.getSpecialist(dto);
        PageInfo<SpecialistResVo.SpecialistVo> pageInfo = new PageInfo<>(specialist);
        SpecialistResVo res = new SpecialistResVo();
        res.setSpecialists(specialist);
        res.setTotalPage(pageInfo.getPages());
        return ResponseResultApp.success(res);
    }


    @ApiOperation("Post consult/ 7")
    @PostMapping("UpdateConSultationNote")
    @Transactional
    public ResponseResultApp UpdateConsultationNote(@RequestBody UpdateConsultationNoteDto dto){
        String curLoginUserId = UserUtil.getCurLoginUserId();
        TblBookingSummary summary = new TblBookingSummary();
        summary.setId(dto.getBookingId());
        summary.setPresentingComplaint(dto.getPresenting_complaint());
        summary.setManagement(dto.getMamagement());
        summary.setInstructionsToPatient(dto.getInstruction_to_patient());
        summary.setPatientTemp(dto.getPatient_temp());
        summary.setPatientBp1(dto.getPatient_bp1());
        summary.setPatientBp2(dto.getPatient_bp2());
        summary.setPatientHr(dto.getPatient_hr());
        summary.setBasicCdmpInformation(dto.getBasic_cdmp_information());
        bookingSummaryService.insertOrUpdate(summary);

        TblBooking booking = new TblBooking();
        booking.setId(dto.getBookingId());
        booking.setFollowUpConsultationNo(dto.getFollow_up_code());
        booking.setDoctorId(curLoginUserId);
        bookingService.insertOrUpdate(booking);
        return ResponseResultApp.success();
    }



    @ApiOperation("Post consult/ 8")
    @PostMapping("UpdateMemberSummary")
    public ResponseResultApp updateMemberSummary(@RequestBody UpdateMemberSummaryDto dto) {

        return service.updateMemberSummary(dto);
    }


    @ApiOperation("Post consult/ 9")
    @PostMapping("UpdateMemo")
    public ResponseResultApp updateMemo(@RequestBody UpdateMemoDto dto) {

        return service.updateMemo(dto);
    }


    @ApiOperation("Post consult/ 10")
    @PostMapping("UpdateReferralLetter")
    public ResponseResultApp updateReferralLetter(@RequestBody UpdateReferralLetterDto dto) {

        return service.updateReferralLetter(dto);
    }


    @ApiOperation("Post consult/ 11")
    @PostMapping("UpdateShowMemo")
    public ResponseResultApp updateShowMemo(@RequestBody UpdateShowMemoDto dto) {

        return service.updateShowMemo(dto);
    }


    /**
     * 来自patientHistory的接口
     */

    @ApiOperation("Patient history/ 1")
    @PostMapping("UpdateBookingMedicalCertificate")
    public ResponseResultApp updateBookingMedicalCertificate(@RequestBody UpdateBookingMedicalCertificateDto dto){
        return service.updateBookingMedicalCertificate(dto);
    }

    @ApiOperation("Patient history/ 2")
    @PostMapping("UpdateBookingMedicalLetter")
    public ResponseResultApp updateBookingMedicalLetter(@RequestBody UpdateBookingMedicalLetterDto dto){

        return service.updateBookingMedicalLetter(dto);
    }

}
